﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.HeaEncyclopeCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.HeaEncyclopeHarder
{
    public class AddHeaEncyclopeHarder : IRequestHandler<AddHeaEncyclopeCommand, APIResult<int>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRepository<HeaEncyclope> repository;
        private readonly ILogger<AddHeaEncyclopeHarder> logger;

        public AddHeaEncyclopeHarder(IMapper mapper, IBaseRepository<HeaEncyclope> repository, ILogger<AddHeaEncyclopeHarder> logger)
        {
            this.mapper = mapper;
            this.repository = repository;
            this.logger = logger;
        }

        public async Task<APIResult<int>> Handle(AddHeaEncyclopeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var xi = mapper.Map<HeaEncyclope>(request);
                xi.IsDeleted = false;
                var a = repository.AddAsync(xi).Result;
                if (a > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = a;
                    logger.LogInformation("新增文章成功");

                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "添加失败";
                    result.Data = a;
                    logger.LogError("新增文章失败");

                }

                return await Task.FromResult(result);

            }
            catch (Exception ex)
            {
                logger.LogError("新增文章异常" + ex.Message);
                throw;
            }
        }
    }
}
